package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import com.heima.media.service.IWmSensitiveService;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmNewsService wmNewsService;

    @Autowired
    private IWmSensitiveService sensitiveService;

    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {

        WmNews wmNews = wmNewsService.getById(id);
        auditService.audit(wmNews);
        return ResponseResult.okResult();
    }

    /**
     * 读取Excel文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/read")
    public ResponseResult readExcel(MultipartFile file) throws IOException {

        //参数1：输入流，参数2：使用哪个类来读取
        EasyExcel.read(file.getInputStream(), WmSensitive.class, new ReadListener<WmSensitive>() {
            @Override
            public void invoke(WmSensitive w, AnalysisContext context) {

                //读取每一行数据触发
                System.out.println(w);

                //更新到数据库中
                //构建查询条件
                LambdaQueryWrapper<WmSensitive> wrapper = new LambdaQueryWrapper<>();
                wrapper.select(WmSensitive::getSensitives);
                List<String> sensitive = sensitiveService.listObjs(wrapper, o -> o.toString());
                //判断集合
                if (!sensitive.contains(w.getSensitives())) {
                    WmSensitive wmSensitive = new WmSensitive();
                    wmSensitive.setCreatedTime(new Date());
                    wmSensitive.setSensitives(w.getSensitives());
                    //保存
                    sensitiveService.save(wmSensitive);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //全部读取完成
                System.out.println("全部读取完成");
            }
        }).sheet().doRead();
        return ResponseResult.okResult();
    }


    @GetMapping("downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        try {
//            int i = 1 / 0;
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), WmSensitive.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(data());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }


    private List<WmSensitive> data() {
        List<WmSensitive> list = sensitiveService.list();
        return list;
    }

}
